<template>
  <div class="app-container">
    <el-row :gutter="10" style="overflow: auto">
      <el-col :xs="4" :sm="5">
        <div class="">
          <catalog
            v-model="parentId"
            :tree-data="tableTreeData"
            :add-node="handleAdd"
            :default-expanded-keys="defaultExpandedKeys"
            @on-search="onSearch"
            @delete-node="handleDelete"
          />
        </div>
      </el-col>
      <el-col :xs="20" :sm="19">
        <el-card shadow="never">
          <template #header class="clearfix">
            <div class="top">
              <span>{{
                deptForm.id === 0 ? $t('message.operate.add') : $t('message.operate.edit')
              }}</span>
              <div>
                <el-button
                  v-limit="'XTGL:JGGL:SAVE'"
                  id="btn"
                  type="primary"
                  plain
                  :loading="editLoading"
                  @click="submitEditForm"
                >
                  {{ $t('message.operate.save') }}
                </el-button>
                <el-button v-limit="'XTGL:JGGL:SYNC'" type="primary" plain @click="pullInstitution">
                  同步机构数据
                </el-button>
              </div>
            </div>
          </template>
          <div>
            <el-form
              ref="deptForm"
              :model="deptForm"
              :rules="dataRule"
              label-position="right"
              label-width="120px"
            >
              <el-row>
                <el-col :span="8">
                  <el-form-item :label="$t('message.org.superior_number')" prop="parentId">
                    <popup-tree-input
                      :data="popupTreeData"
                      :props="popupTreeProps"
                      :prop="
                        deptForm.parentName == null
                          ? $t('message.org.top_menu')
                          : deptForm.parentName
                      "
                      :node-key="'' + deptForm.parentId"
                      :current-change-handle="handleTreeSelectChange"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('message.org.type')" prop="orgType">
                    <el-select
                      v-model="deptForm.orgType"
                      style="width: 100%"
                      clearable
                      :placeholder="$t('message.validate.select_type')"
                      @change="onChangeOrg"
                    >
                      <el-option
                        v-for="{ itemText, itemValue } of types"
                        :key="Number(itemValue)"
                        :label="itemText"
                        :value="Number(itemValue)"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('message.form.sort')" prop="sort">
                    <el-input-number
                      v-model="deptForm.sort"
                      style="width: 100%"
                      :min="0"
                      :max="100"
                      @change="handleNumChange"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item :label="$t('message.org.name')" prop="name">
                    <el-input v-model="deptForm.name" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('message.org.abbreviation')" prop="shortName">
                    <el-input v-model="deptForm.shortName" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    :label="$t('message.org.OrgCode')"
                    prop="code"
                    :rules="{
                      required: deptForm.orgType === 1,
                      message: $t('message.validate.required'),
                      trigger: 'blur',
                    }"
                  >
                    <el-input v-model="deptForm.code" :disabled="deptForm.orgType === 3" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <!-- <el-col :span="8">
                  <el-form-item :label="$t('message.org.aaaaOrgName')" prop="aaaaList">
                    <el-select v-model="deptForm.aaaaOrgName" multiple placeholder="请选择">
                      <el-option
                        v-for="item in aaaaOrgNameOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                    <only-tree-select
                      v-model:value="deptForm.aaaaList"
                      :default-checked-keys="defaultSelectedOrgs"
                      :tree-data="aaaaOrgNameOptions"
                      node-key="oid"
                      :props="{
                        label: 'name',
                        children: 'children',
                      }"
                      :disabled="deptForm.orgType === 3"
                    />
                  </el-form-item>
                </el-col> -->
                <el-col :span="8">
                  <!-- 单位类型 -->
                  <el-form-item
                    :label="$t('message.post.flatType')"
                    prop="unitType"
                    :rules="{
                      required: deptForm.orgType === 1,
                      message: $t('message.validate.required'),
                      trigger: 'blur',
                    }"
                  >
                    <el-select
                      v-model="deptForm.unitType"
                      style="width: 100%"
                      :disabled="deptForm.orgType != 1"
                      clearable
                      @change="handleChange"
                    >
                      <el-option
                        v-for="{ itemText, itemValue } of unitTypeOptions"
                        :key="itemValue"
                        :label="itemText"
                        :value="itemValue"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <!-- 资产类型 -->
                  <el-form-item
                    :label="$t('message.org.assetType')"
                    prop="assetTypeCompany"
                    :rules="{
                      required:
                        deptForm.orgType === 1 &&
                        (deptForm.unitType == 'road' || deptForm.unitType == 'ProjectOperating'),
                      message: $t('message.validate.required'),
                      trigger: 'blur',
                    }"
                  >
                    <el-cascader
                      v-model="deptForm.assetTypeCompany"
                      style="width: 100%"
                      clearable
                      :options="assetTypeCompanys"
                      :disabled="
                        deptForm.orgType === 1 &&
                        (deptForm.unitType === 'road' || deptForm.unitType === 'ProjectOperating')
                          ? false
                          : true
                      "
                    ></el-cascader>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item :label="$t('message.org.contactName')" prop="contactName">
                    <el-input v-model="deptForm.contactName" :disabled="deptForm.orgType === 3" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('message.org.contactPhone')" prop="contactPhone">
                    <el-input
                      v-model="deptForm.contactPhone"
                      :disabled="deptForm.orgType === 3"
                      autosize=""
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item :label="$t('message.org.region')" prop="region">
                    <el-select
                      v-model="deptForm.region"
                      placeholder="请选择"
                      clearable
                      style="width: 100%"
                      :disabled="deptForm.orgType != 1"
                    >
                      <el-option
                        v-for="item in regionOptions"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item
                    :key="forceUpdateKey"
                    :label="$t('message.org.dept_leader')"
                    prop="leader"
                  >
                    <user-list-modal
                      v-model="deptForm.leader"
                      :multiple="false"
                      :default-users="leaderOption"
                      :orgid="orgid"
                      :disabled="!isLeader"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    :key="forceUpdateKey"
                    :label="$t('message.post.deptHeader')"
                    prop="departmentHead"
                  >
                    <user-list-modal
                      v-model="deptForm.departmentHeadName"
                      :multiple="false"
                      @update:modelValue="handleDepartmentHead"
                      :default-users="deptHeaderOption"
                      :orgid="orgid"
                      :devType="'platform'"
                      :disabled="!isLeader"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item
                    :label="$t('message.org.companyStatus')"
                    prop="companyStatus"
                    :rules="{
                      required: deptForm.orgType === 1,
                      message: $t('message.validate.required'),
                      trigger: 'blur',
                    }"
                  >
                    <el-select
                      v-model="deptForm.companyStatus"
                      style="width: 100%"
                      :placeholder="$t('message.validate.select_type')"
                      :disabled="deptForm.orgType != 1"
                      clearable
                    >
                      <el-option
                        v-for="{ itemText, itemValue } of companyStatuses"
                        :key="itemValue"
                        :label="itemText"
                        :value="itemValue"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import PopupTreeInput from '../components/PopupTreeInput'
// import UserListModal from '../components/UserListModal'
import UserListModal from '@/views/project/components/UserListModal/index.vue'
import {
  saveOrg,
  getOrgTree,
  updateOrg,
  deleteOrg,
  getRegionOptions,
  get4AOrg,
  get4AOrgData,
  getUserById,
  syncCompany,
  syncInstitution,
} from '../api/org'
import { parseTime } from '@/utils/index'
// import { get, find } from 'lodash'
import { useDict } from '../utils/useDict'
import Catalog from '../components/Catalog'
// import PopupTreeSelect from '@/components/PopupTreeSelect'
import OnlyTreeSelect from '../components/OnlyTreeSelect'
import { dataDictionary } from '../api/dict'
import { isEmpty } from 'lodash'
import { servicesLoading } from '@/views/project/project-manage/loading'
// import Cookies from 'js-cookie'

const deptForm = {
  id: 0,
  name: '',
  leader: '',
  parentId: 0,
  parentName: '',
  sort: 0,
  orgType: '',
  regionList: [],
  unitType: '', // 单位类型
  departmentHead: '', // 部门负责人
  code: '',
  aaaaList: [],
  region: '',
  contactName: '',
  contactPhone: '',
  shortName: '',
  companyStatus: '',
  assetTypeCompany: '',
}

export default {
  components: { PopupTreeInput, UserListModal, Catalog, OnlyTreeSelect },
  setup() {
    const types = useDict(10006)
    const unitTypeOptions = useDict(10005)
    return {
      types,
      unitTypeOptions,
    }
  },
  data() {
    return {
      parentId: '',
      orgid: '',
      deptForm,
      dictCatalog: [],
      tableTreeData: [
        {
          children: [],
          dictName: this.$i18n.t('message.dict.top'),
          id: undefined,
        },
      ],
      popupTreeData: [],
      leaderOption: [],
      deptHeaderOption: [],
      popupTreeProps: {
        label: 'name',
        children: 'children',
      },
      editLoading: false,
      deptName: '',
      isLeader: false,
      forceUpdateKey: Math.random(), // 强制刷新组件
      regionOptions: [],
      aaaaOrgNameOptions: [],
      defaultSelectedOrgs: [],
      companyStatuses: [],
      assetTypeCompanys: [],
      defaultExpandedKeys: [],
    }
  },
  computed: {
    dataRule() {
      return {
        name: {
          required: true,
          message: this.$i18n.t('message.validate.required'),
          trigger: 'blur',
        },
        parentId: {
          required: true,
          message: this.$i18n.t('message.validate.required'),
          trigger: 'blur',
        },
        shortName: {
          required: true,
          message: this.$i18n.t('message.validate.required'),
          trigger: 'blur',
        },
        parentName: {
          required: true,
          message: this.$i18n.t('message.validate.required'),
          trigger: 'blur',
        },
        sort: {
          required: true,
          message: this.$i18n.t('message.validate.required'),
          trigger: 'blur',
        },
        leader: [
          {
            required: false,
            message: this.$i18n.t('message.validate.required'),
            trigger: 'blur',
          },
        ],
        orgType: [
          {
            required: true,
            message: this.$i18n.t('message.validate.required'),
            trigger: 'blur',
          },
        ],
        principal: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'change' },
        ],
        departmentHead: [
          {
            required: false,
            message: this.$i18n.t('message.validate.required'),
            trigger: 'change',
          },
        ],
        unitType: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'change' },
        ],
        region: [
          {
            required: false,
            message: this.$i18n.t('message.validate.required'),
            trigger: 'change',
          },
        ],
        aaaaList: [
          {
            required: false,
            message: this.$i18n.t('message.validate.required'),
            trigger: 'change',
          },
        ],
        contactName: [
          {
            required: false,
            message: this.$i18n.t('message.validate.required'),
            trigger: 'change',
          },
        ],
        contactPhone: [
          {
            required: false,
            message: this.$i18n.t('message.validate.required'),
            trigger: 'change',
          },
        ],
        companyStatus: [
          {
            required: true,
            message: this.$i18n.t('message.validate.required'),
            trigger: 'change',
          },
        ],
        assetTypeCompany: [
          {
            required: true,
            message: this.$i18n.t('message.validate.required'),
            trigger: 'change',
          },
        ],
      }
    },
    userList() {
      const { userList } = this.$store.state.userList
      return userList
    },
  },
  mounted() {
    this.findTreeData()
    this.$store.dispatch('userList/fetchUserList')
  },
  methods: {
    parseTime,
    // 点击节点
    handleNodeClick(data) {
      let nowdata = data
      this.isLeader = nowdata.orgType === 2 || false
      this.deptHeaderOption = []
      this.leaderOption = []
      if (!isEmpty(nowdata.leader)) {
        getUserById(nowdata.leader).then((res) => {
          this.leaderOption = [res.data.data || {}]
          this.orgid = nowdata.id ?? '10000'
        })
        getUserById(nowdata.departmentHead).then((res) => {
          this.deptHeaderOption = [res.data.data || {}]
        })
      }
      // this.deptHeaderOption = [get(nowdata, 'departmentHeadUser') || {}]
      // this.leaderOption = [get(nowdata, 'leaderUser') || {}]

      this.deptForm = { ...nowdata }
      this.forceUpdateKey = Math.random() // 刷新组件
      this.$refs.deptForm.clearValidate()

      get4AOrgData({ orgid: nowdata.id ?? '10000' }).then((res) => {
        this.defaultSelectedOrgs = res.data?.data ?? []
      })
    },
    onSearch(data) {
      this.handleNodeClick(data)
    },
    handleNumChange(val) {
      this.deptForm.sort = val
    },
    handleChange(val) {
      if (val != 'road' && val != 'ProjectOperating') {
        this.deptForm.assetTypeCompany = ''
      }
    },
    handleDepartmentHead (user) {
      console.log(user, 'handleProjectLeader')
      this.deptForm.departmentHead = user.userId
      this.deptForm.departmentHeadName = `${user.cname}`
    },
    // 显示新增界面
    handleAdd(initialValues = {}, dictName = '') {
      this.isLeader = false
      this.deptForm = {
        id: 0,
        name: '',
        parentId: initialValues.parentId,
        orgType: 1,
        parentName: dictName || '顶级菜单',
        sort: 0,
        // orgTypeName: '',
        // regionList: [],
        // unitType: '', // 单位类型
        // departmentHead: '', // 部门负责人
        // code: '',
        // aaaaList: [],
        // region: '',
        // contactName: '',
        // contactPhone: '',
        // shortName: '',
        // companyStatus: '',
        // assetTypeCompany: '',
      }
    },
    toggleIsLeader(value) {
      this.isLeader = value
    },
    onChangeOrg(value) {
      this.isLeader = value === 2 || false
      this.deptForm.unitType = ''
      if (value == 3) {
        // this.deptForm.unitType='', // 单位类型
        ;(this.deptForm.departmentHead = ''), // 部门负责人
          (this.deptForm.code = ''),
          (this.deptForm.aaaaList = []),
          (this.deptForm.region = ''),
          (this.deptForm.contactName = ''),
          (this.deptForm.contactPhone = ''),
          (this.deptForm.companyStatus = ''),
          (this.deptForm.assetTypeCompany = '')
      }
    },
    // 获取数据
    findTreeData() {
      this.loading = true
      function ifDisable(arr) {
        let nowArr = arr
        nowArr.map(function (item) {
          ;(item.value = item.itemValue), (item.label = item.itemText)
          if (item.orgType != 2) {
            item.disabled = true
          }
          if (item.children && item.children.length) {
            ifDisable(item.children)
          }
        })
        return nowArr
      }
      getOrgTree().then((res) => {
        this.dictCatalog = res.data.data
        this.tableTreeData = this.dictCatalog
        // this.treeSelectData[0].children = this.dictCatalog
        this.defaultExpandedKeys = this.dictCatalog.map((item) => item.id)
        // treeSelectData: [
        //   {
        //     children: [],
        //     dictName: this.$i18n.t('message.dict.top'),
        //     id: undefined,
        //   },
        // ],
        //获取上级机构
        this.popupTreeData = res.data.data
        // this.popupTreeData = this.getParentMenuTree(res.data.data)
        this.loading = false
      })
      //获取行政区域
      getRegionOptions({ regionCode: '000000000000' }).then((rst) => {
        if (rst?.data && rst?.data?.code === 200) {
          this.regionOptions = rst.data.data.children.map((item) => ({
            value: item.regionCode,
            label: item.regionName,
          }))
        }
      })
      //获取4A机构树
      get4AOrg().then((res) => {
        if (res?.data && res?.data?.code === 200) {
          // this.aaaaOrgNameOptions=ifDisable(res.data.data)
          this.aaaaOrgNameOptions = res.data.data
        }
      })
      //查询字典
      dataDictionary(['COMPANY_STATUS', 'ASSET_TYPE_COMPANY']).then((res) => {
        this.companyStatuses = res.data.data.COMPANY_STATUS
        this.assetTypeCompanys = ifDisable(res.data.data.ASSET_TYPE_COMPANY)
      })
    },
    // 获取上级机构树
    getParentMenuTree(tableTreeDdata) {
      const parent = {
        parentId: 0,
        name: '顶级菜单',
        children: tableTreeDdata,
      }
      return [parent]
    },
    // 机构树选中
    handleTreeSelectChange(data) {
      this.deptForm.parentId = data.id
      this.deptForm.parentName = data.name
      this.$refs.deptForm.clearValidate()
    },
    submitEditForm() {
      this.$refs['deptForm'].validate((valid) => {
        if (valid) {
          console.log(this.deptForm.assetTypeCompany)

          if (
            this.deptForm.assetTypeCompany != null &&
            this.deptForm.assetTypeCompany != '' &&
            typeof this.deptForm.assetTypeCompany == 'object'
          ) {
            this.deptForm.assetTypeCompany = this.deptForm.assetTypeCompany[
              this.deptForm.assetTypeCompany.length - 1
            ]
          }

          if (this.deptForm.id) {
            this.$confirm('确认提交吗？', this.$i18n.t('message.operate.hint'), {}).then(() => {
              this.editLoading = true
              updateOrg(this.deptForm).then((res) => {
                if (res.data.code === 200) {
                  this.$message({ message: res.data.msg, type: 'success' })
                } else {
                  this.$message({ message: res.data.msg, type: 'error' })
                }
                this.$refs.deptForm.clearValidate()
                this.findTreeData()
              })
              this.editLoading = false
            })
          } else {
            const params = {
              ...this.deptForm,
              regionList: [],
            }
            this.$confirm('确认提交吗？', this.$i18n.t('message.operate.hint'), {}).then(() => {
              this.editLoading = true
              saveOrg(params).then((res) => {
                if (res.data.code === 200) {
                  this.$message({ message: res.data.msg, type: 'success' })
                  this.deptForm.id = res.data.data
                } else {
                  this.$message({ message: res.data.msg, type: 'error' })
                }
                this.$refs.deptForm.clearValidate()
                this.findTreeData()
              })
              this.editLoading = false
            })
          }
        }
      })
    },
    pullInstitution() {
      this.$confirm('确定要同步中咨系统机构数据吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        const loading = servicesLoading({ fullscreen: false })
        syncCompany().then(() => {
          this.$message({
            type: 'success',
            message: '同步公司数据成功',
          })
          loading.close()
          this.adminList()
        })
        syncInstitution().then(() => {
          this.$message({
            type: 'success',
            message: '同步部门数据成功',
          })
          loading.close()
          this.adminList()
        })
      })
    },
    // 删除
    handleDelete(dicId) {
      let deleteId = dicId
      const that = this
      if (deleteId === 0) {
        this.$message({
          message: '请先选择一个机构哦',
          type: 'warning',
        })
      } else {
        this.$confirm('此操作将把机构删除, 是否继续?', this.$i18n.t('message.operate.hint'), {
          confirmButtonText: this.$i18n.t('message.operate.confirm'),
          cancelButtonText: this.$i18n.t('message.operate.cancel'),
          type: 'warning',
        }).then(() => {
          deleteOrg(deleteId).then((response) => {
            if (response.data.code === 200) {
              this.$message({
                type: 'success',
                message: response.data.msg,
              })
              that.findTreeData()
            } else {
              this.$message({ message: response.data.msg, type: 'error' })
            }
          })
          this.deptForm = {
            id: 0,
            name: '',
            principal: null,
            leader: '',
            parentId: 0,
            parentName: '',
            sort: 0,
            orgType: '',
            orgTypeName: '',
            regionList: [],
            unitType: '', // 单位类型
            departmentHead: '', // 部门负责人
            code: '',
            aaaaList: [],
            region: '',
            contactName: '',
            contactPhone: '',
            shortName: '',
            companyStatus: '',
            assetTypeCompany: '',
          }
          this.$refs.deptForm.clearValidate()
        })
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.el-card {
  border-radius: 0;
  border: none;

  .el-card__header {
    padding: 10px 20px !important;
    border-bottom: 1px solid #f1f1f1 !important;
  }
}
.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
